<template>
  <view class="vehicle-color-stats-container">
    <z-paging 
      ref="paging" 
      v-model="dataList" 
      @query="queryList"
      :auto="false"
      :refresher-enabled="true"
      :loading-more-enabled="true"
      :empty-view-text="'暂无数据'"
      class="list-paging"
    >
      <template #top>
        <!-- 页面标题 -->
        <view class="page-header">
          <view class="header-title">车牌颜色统计</view>
        </view>
        
        <!-- 筛选区域 -->
        <view class="filter-section">
          <view class="filter-row">
            <view class="filter-item">
              <text class="filter-label">统计周期：</text>
              <picker mode="selector" :value="filters.periodIndex" :range="periodOptions" @change="onPeriodChange">
                <view class="date-picker">
                  <text>{{ filters.periodIndex >= 0 ? periodOptions[filters.periodIndex] : '请选择' }}</text>
                  <up-icon name="arrow-down" size="14"></up-icon>
                </view>
              </picker>
            </view>
            
            <view class="filter-item">
              <text class="filter-label">停车场：</text>
              <picker :value="filters.parkingLotIndex" :range="parkingLotOptions" @change="onParkingLotChange">
                <view class="date-picker">
                  <text>{{ filters.parkingLotIndex >= 0 ? parkingLotOptions[filters.parkingLotIndex] : '全部' }}</text>
                  <up-icon name="arrow-down" size="14"></up-icon>
                </view>
              </picker>
            </view>
          </view>
          
          <view class="filter-row">
            <view class="filter-item">
              <text class="filter-label">车牌颜色：</text>
              <picker :value="filters.plateColorIndex" :range="colorTypes.map(item => item.name)" @change="onPlateColorChange">
                <view class="date-picker">
                  <text>{{ filters.plateColorIndex >= 0 ? colorTypes[filters.plateColorIndex].name : '全部' }}</text>
                  <up-icon name="arrow-down" size="14"></up-icon>
                </view>
              </picker>
            </view>
          </view>
          
          <view class="filter-actions">
            <button class="search-btn" @click="searchData">查询</button>
            <button class="reset-btn" @click="resetFilters">重置</button>
          </view>
        </view>
        
        <!-- 统计摘要 -->
        <view class="summary-section">
          <view class="summary-card">
            <view class="summary-title">车辆总数</view>
            <view class="summary-value">{{ summary.totalVehicles }}</view>
          </view>
          <view class="summary-card">
            <view class="summary-title">平均停留时间</view>
            <view class="summary-value">{{ summary.avgStayTime }}</view>
          </view>
          <view class="summary-card">
            <view class="summary-title">高峰时段</view>
            <view class="summary-value">{{ summary.peakHours }}</view>
          </view>
        </view>
        
        <!-- 列表表头 -->
        <view class="list-header">
          <text class="list-cell">车牌颜色</text>
          <text class="list-cell">车辆数量</text>
          <text class="list-cell">占比</text>
          <text class="list-cell">平均停留时间</text>
          <text class="list-cell">高峰时段</text>
        </view>
      </template>
      
      <!-- 列表内容 -->
      <view v-for="(item, index) in dataList" :key="index" class="list-row" @click="showDetail(item)">
        <view class="list-cell color-cell">
          <view class="color-block" :style="{ backgroundColor: item.colorHex }"></view>
          {{ item.colorName }}
        </view>
        <text class="list-cell">{{ item.vehicleCount }}</text>
        <text class="list-cell">{{ item.percentage }}%</text>
        <text class="list-cell">{{ item.avgStayTime }}</text>
        <text class="list-cell">{{ item.peakHours }}</text>
      </view>
    </z-paging>
    
    <!-- 详情弹窗 -->
    <view class="detail-modal" v-if="showDetailModal">
      <view class="detail-content">
        <view class="detail-header">
          <text class="detail-title">详情信息</text>
          <text class="close-btn" @click="showDetailModal = false">×</text>
        </view>
        
        <view class="detail-body" v-if="currentDetail">
          <view class="detail-item">
            <text class="detail-label">车牌颜色：</text>
            <view class="detail-value color-detail">
              <view class="color-block" :style="{ backgroundColor: currentDetail.colorHex }"></view>
              {{ currentDetail.colorName }}
            </view>
          </view>
          
          <view class="detail-item">
            <text class="detail-label">统计周期：</text>
            <text class="detail-value">{{ periodOptions[filters.periodIndex] }}</text>
          </view>
          
          <view class="detail-item">
            <text class="detail-label">车辆数量：</text>
            <text class="detail-value">{{ currentDetail.vehicleCount }}</text>
          </view>
          
          <view class="detail-item">
            <text class="detail-label">占比：</text>
            <text class="detail-value">{{ currentDetail.percentage }}%</text>
          </view>
          
          <view class="detail-item">
            <text class="detail-label">平均停留时间：</text>
            <text class="detail-value">{{ currentDetail.avgStayTime }}</text>
          </view>
          
          <view class="detail-item">
            <text class="detail-label">高峰时段：</text>
            <text class="detail-value">{{ currentDetail.peakHours }}</text>
          </view>
          
          <view class="detail-item" v-if="currentDetail.popularModels && currentDetail.popularModels.length > 0">
            <text class="detail-label">常见车型：</text>
            <view class="detail-value">
              <view v-for="(model, idx) in currentDetail.popularModels" :key="idx" class="model-item">
                {{ model.name }}: {{ model.count }}辆
              </view>
            </view>
          </view>
          
          <view class="detail-item" v-if="currentDetail.popularModels && currentDetail.popularModels.length > 0">
            <text class="detail-label">常见车型：</text>
            <view class="detail-value">
              <view v-for="(model, idx) in currentDetail.popularModels" :key="idx" class="model-item">
                {{ model.name }}: {{ model.count }}辆
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, computed } from 'vue'

// 筛选条件
const filters = reactive({
  periodIndex: 0,
  parkingLotIndex: 0,
  plateColorIndex: -1
})

// 统计周期选项
const periodOptions = [
  '日统计',
  '月统计',
  '年统计'
]

// 停车场选项
const parkingLotOptions = [
  '全部',
  'A区停车场',
  'B区停车场',
  'C区停车场',
  'D区停车场'
]

// 列表数据
const dataList = ref([])
const paging = ref(null)

// 定义车牌颜色类型
const colorTypes = [
  { name: '蓝牌', hex: '#0000FF' },
  { name: '绿牌', hex: '#008000' },
  { name: '黄牌', hex: '#FFFF00' },
  { name: '白牌', hex: '#FFFFFF' },
  { name: '黑牌', hex: '#000000' },
  { name: '渐变绿牌', hex: '#00FF00' }
]

// 统计摘要数据
const summary = reactive({
  totalVehicles: 0,
  avgStayTime: '',
  peakHours: ''
})

// 详情弹窗
const showDetailModal = ref(false)
const currentDetail = ref(null)

// 统计周期选择处理
const onPeriodChange = (e) => {
  filters.periodIndex = parseInt(e.detail.value)
}

// 停车场选择处理
const onParkingLotChange = (e) => {
  filters.parkingLotIndex = parseInt(e.detail.value)
}

// 查询数据
const searchData = () => {
  if (paging.value) {
    paging.value.reload()
  }
}

// 重置筛选条件
const resetFilters = () => {
  filters.periodIndex = 0
  filters.parkingLotIndex = 0
  filters.plateColorIndex = -1
  
  nextTick(() => {
    if (paging.value) {
      paging.value.reload()
    }
  })
}

// 车牌颜色选择处理
const onPlateColorChange = (e) => {
  filters.plateColorIndex = parseInt(e.detail.value)
}

// 查询列表数据
const queryList = (pageNo, pageSize) => {
  // 模拟请求延迟
  setTimeout(() => {
    // 生成模拟数据
    const data = generateMockData(pageNo, pageSize)
    paging.value.complete(data)
    
    // 更新统计摘要
    updateSummary(data)
  }, 500)
}

// 更新统计摘要
const updateSummary = (data) => {
  // 计算车辆总数
  let totalCount = 0
  data.forEach(item => {
    totalCount += item.vehicleCount
  })
  summary.totalVehicles = totalCount
  
  // 计算平均停留时间（模拟数据）
  const stayTimeHours = Math.floor(Math.random() * 4) + 1
  const stayTimeMinutes = Math.floor(Math.random() * 60)
  summary.avgStayTime = `${stayTimeHours}小时${stayTimeMinutes}分钟`
  
  // 确定高峰时段（模拟数据）
  const peakStartHour = Math.floor(Math.random() * 12) + 7 // 7点到18点之间
  const peakEndHour = peakStartHour + Math.floor(Math.random() * 3) + 1 // 持续1-3小时
  summary.peakHours = `${peakStartHour}:00-${peakEndHour}:00`
}

// 生成模拟数据
const generateMockData = (pageNo, pageSize) => {
  const data = []
  
  // 停车场列表
  const parkingLots = parkingLotOptions.slice(1) // 排除"全部"选项
  
  // 计算总车辆数（用于计算占比）
  const totalVehicles = Math.floor(Math.random() * 5000) + 2000
  let remainingVehicles = totalVehicles
  
  // 筛选颜色类型
  let filteredColorTypes = [...colorTypes]
  if (filters.plateColorIndex >= 0) {
    filteredColorTypes = [colorTypes[filters.plateColorIndex]]
  }
  
  // 生成随机数据
  for (let i = 0; i < filteredColorTypes.length; i++) {
    const currentColor = filteredColorTypes[i]
    
    // 根据颜色类型确定车辆数量分布
    let vehicleCount
    if (i === colorTypes.length - 1) {
      // 最后一个颜色使用剩余车辆数
      vehicleCount = remainingVehicles
    } else {
      // 根据颜色类型设置不同的车辆数量分布
      let percentage
      if (currentColor.name === '黑色' || currentColor.name === '白色' || currentColor.name === '银灰色') {
        percentage = Math.random() * 0.15 + 0.15 // 15%-30%
      } else if (currentColor.name === '红色' || currentColor.name === '蓝色') {
        percentage = Math.random() * 0.1 + 0.05 // 5%-15%
      } else {
        percentage = Math.random() * 0.05 + 0.01 // 1%-6%
      }
      vehicleCount = Math.floor(totalVehicles * percentage)
      remainingVehicles -= vehicleCount
    }
    
    // 计算占比
    const percentage = ((vehicleCount / totalVehicles) * 100).toFixed(2)
    
    // 生成停车场分布
    const parkingLotDetails = []
    let remainingForLots = vehicleCount
    
    for (let j = 0; j < parkingLots.length; j++) {
      let lotCount
      if (j === parkingLots.length - 1) {
        lotCount = remainingForLots
      } else {
        lotCount = Math.floor(vehicleCount * (Math.random() * 0.4 + 0.1)) // 10%-50%
        remainingForLots -= lotCount
      }
      
      const lotPercentage = ((lotCount / vehicleCount) * 100).toFixed(2)
      
      parkingLotDetails.push({
        name: parkingLots[j],
        count: lotCount,
        percentage: lotPercentage
      })
    }
    
    // 生成常见车型
    const carModels = ['大众', '丰田', '本田', '福特', '现代', '别克', '宝马', '奔驰', '奥迪', '雪佛兰']
    const popularModels = []
    let remainingForModels = vehicleCount
    
    // 随机选择3-5个车型
    const modelCount = Math.floor(Math.random() * 3) + 3
    const selectedModels = [...carModels].sort(() => 0.5 - Math.random()).slice(0, modelCount)
    
    for (let k = 0; k < selectedModels.length; k++) {
      let modelCount
      if (k === selectedModels.length - 1) {
        modelCount = remainingForModels
      } else {
        modelCount = Math.floor(vehicleCount * (Math.random() * 0.3 + 0.1)) // 10%-40%
        remainingForModels -= modelCount
      }
      
      popularModels.push({
        name: selectedModels[k],
        count: modelCount
      })
    }
    
    // 不再需要生成停车场分布描述
    
    // 生成平均停留时间（模拟数据）
    const stayTimeHours = Math.floor(Math.random() * 4) + 1
    const stayTimeMinutes = Math.floor(Math.random() * 60)
    const avgStayTime = `${stayTimeHours}小时${stayTimeMinutes}分钟`
    
    // 生成高峰时段（模拟数据）
    const peakStartHour = Math.floor(Math.random() * 12) + 7 // 7点到18点之间
    const peakEndHour = peakStartHour + Math.floor(Math.random() * 3) + 1 // 持续1-3小时
    const peakHours = `${peakStartHour}:00-${peakEndHour}:00`
    
    // 添加数据
    data.push({
      id: i + 1,
      colorName: currentColor.name,
      colorHex: currentColor.hex,
      vehicleCount,
      percentage,
      popularModels,
      avgStayTime,
      peakHours
    })
  }
  
  // 根据车辆数量排序（从多到少）
  return data.sort((a, b) => b.vehicleCount - a.vehicleCount)
}

// 显示详情
const showDetail = (item) => {
  // 为详情添加平均停留时间和高峰时段数据
  const stayTimeHours = Math.floor(Math.random() * 4) + 1
  const stayTimeMinutes = Math.floor(Math.random() * 60)
  const stayTime = `${stayTimeHours}小时${stayTimeMinutes}分钟`
  
  const peakStartHour = Math.floor(Math.random() * 12) + 7 // 7点到18点之间
  const peakEndHour = peakStartHour + Math.floor(Math.random() * 3) + 1 // 持续1-3小时
  const peakHours = `${peakStartHour}:00-${peakEndHour}:00`
  
  currentDetail.value = {
    ...item,
    avgStayTime: stayTime,
    peakHours: peakHours
  }
  showDetailModal.value = true
}

// 页面加载
onMounted(() => {
  // 页面挂载时获取数据
  nextTick(() => {
    if (paging.value) {
      paging.value.reload()
    }
  })
})
</script>

<style lang="scss" scoped>
.vehicle-color-stats-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.list-paging {
  flex: 1;
  height: 100%;
}

.page-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 40rpx 30rpx 30rpx;
  color: white;
  
  .header-title {
    font-size: 36rpx;
    font-weight: bold;
    text-align: center;
  }
}

.filter-section {
  background: white;
  margin: 20rpx;
  padding: 30rpx;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
  
  .filter-row {
    display: flex;
    margin-bottom: 20rpx;
    
    &:last-child {
      margin-bottom: 0;
    }
  }
  
  .filter-item {
    flex: 1;
    margin-right: 20rpx;
    
    &:last-child {
      margin-right: 0;
    }
    
    &.full-width {
      flex: none;
      width: 100%;
      margin-right: 0;
    }
  }
  
  .filter-label {
    font-size: 28rpx;
    color: #333;
    margin-bottom: 10rpx;
    display: block;
  }
  
  .date-picker,
  .picker-input {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20rpx;
    border: 2rpx solid #e0e0e0;
    border-radius: 10rpx;
    background: #fafafa;
    font-size: 26rpx;
    color: #666;
  }
  
  .filter-actions {
    display: flex;
    gap: 20rpx;
    margin-top: 30rpx;
  }
  
  .search-btn,
  .reset-btn {
    flex: 1;
    padding: 20rpx;
    border-radius: 10rpx;
    font-size: 28rpx;
    border: none;
  }
  
  .search-btn {
    background: #1890FF;
    color: white;
  }
  
  .reset-btn {
    background: #f0f0f0;
    color: #666;
  }
}

.summary-section {
  display: flex;
  justify-content: space-between;
  margin: 0 20rpx 20rpx;
  
  .summary-card {
    flex: 1;
    background: white;
    border-radius: 10rpx;
    padding: 20rpx;
    margin: 0 10rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
    text-align: center;
    
    &:first-child {
      margin-left: 0;
    }
    
    &:last-child {
      margin-right: 0;
    }
    
    .summary-title {
      font-size: 24rpx;
      color: #666;
      margin-bottom: 10rpx;
    }
    
    .summary-value {
      font-size: 32rpx;
      color: #333;
      font-weight: bold;
    }
  }
}

.list-header {
  display: flex;
  background: #f0f0f0;
  padding: 20rpx;
  margin: 0 20rpx;
  border-radius: 10rpx 10rpx 0 0;
  font-size: 26rpx;
  font-weight: bold;
  color: #333;
}

.list-row {
  display: flex;
  background: white;
  padding: 20rpx;
  margin: 0 20rpx;
  border-bottom: 2rpx solid #f0f0f0;
  font-size: 26rpx;
  color: #666;
  
  &:last-child {
    border-radius: 0 0 10rpx 10rpx;
    margin-bottom: 20rpx;
  }
}

.list-cell {
  flex: 1;
  text-align: center;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  padding: 0 5rpx;
  font-size: 24rpx;
}

.color-cell {
  display: flex;
  align-items: center;
  justify-content: center;
}

.color-block {
  width: 30rpx;
  height: 30rpx;
  border-radius: 6rpx;
  margin-right: 10rpx;
  border: 1px solid #ddd;
}

.detail-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 999;
}

.detail-content {
  width: 80%;
  max-height: 80%;
  background: white;
  border-radius: 20rpx;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  background: #f5f5f5;
  border-bottom: 2rpx solid #e0e0e0;
  
  .detail-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
  }
  
  .close-btn {
    font-size: 40rpx;
    color: #999;
    line-height: 1;
  }
}

.detail-body {
  padding: 30rpx;
  overflow-y: auto;
}

.detail-item {
  display: flex;
  margin-bottom: 20rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
  
  .detail-label {
    width: 200rpx;
    font-size: 28rpx;
    color: #666;
  }
  
  .detail-value {
    flex: 1;
    font-size: 28rpx;
    color: #333;
  }
}

.color-detail {
  display: flex;
  align-items: center;
}

.parking-lot-item,
.model-item {
  margin-bottom: 10rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}
</style>